package com.mydesign.demo.service.Impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mydesign.demo.bean.Store;
import com.mydesign.demo.bean.StoreExample;
import com.mydesign.demo.bean.Wxuser;
import com.mydesign.demo.bean.WxuserExample;
import com.mydesign.demo.mapper.StoreMapper;
import com.mydesign.demo.mapper.WxuserMapper;
import com.mydesign.demo.model.ReturnResult;
import com.mydesign.demo.service.WxUserService;
import com.mydesign.demo.util.AesCbcUtil;
import com.mydesign.demo.util.HttpUtil;
import com.mydesign.demo.util.JWTUtils;
import com.mydesign.demo.util.RandomUtil18;
import com.mydesign.demo.util.WxUtil.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxUserServiceImpl implements WxUserService {
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Override
    public Map getWxUserOpenid(String encryptedData,String iv,String code) {
        String appId = WeChatConfig.appid;
        String appSecret = WeChatConfig.appsecret;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        /**RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url,"",String.class);
        System.out.println("获取到的数据：????"+responseEntity.getBody());**/
        String data = HttpUtil.requestCheckUpdateJson(url);
        System.err.println("获取到的数据：》》》"+data);
        Map<String,String> map = JSON.parseObject(data, Map.class);
        String session_key = map.get("session_key");
        String result = "";
        try {
            byte[] res = AesCbcUtil.decrypt(encryptedData, session_key, iv);
            result = new String(res,"utf-8");
        } catch (Exception e)  {
            return null ;
        }
        if (null != result && result.length() > 0) {
            JSONObject userInfoJSON = JSONObject.parseObject(result);
            System.err.println(userInfoJSON.toJSONString());
            HashMap<String, Object> userInfo = new HashMap<>();
            userInfo.put("wx_openid", map.get("openid"));
            userInfo.put("wx_nickname", userInfoJSON.get("nickName"));
            userInfo.put("wx_headimgurl", userInfoJSON.get("avatarUrl"));
            //userInfo.put("wx_unionid", map.get("unionId"));
            Object wx_openid = userInfo.get("wx_openid");
            System.out.println(wx_openid.toString());
            Map<String, String> userMap=new HashMap<>();
//            String openId = userInfoJSON.get("openId").toString();
            userMap.put("openid",map.get("openid"));
            //userMap.put("userid", RandomUtil18.Number18());
            return userMap;
        }else {
            System.err.println("解密失败");
        }
        return null;
    }

    @Override
    public ReturnResult WxUserRegister(HttpServletRequest request) {
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        String code = request.getParameter("code");
        Map<String, String> wxUserOpenid = getWxUserOpenid(encryptedData, iv, code);
        String openid = wxUserOpenid.get("openid");
        WxuserExample wxuserExample=new WxuserExample();
        wxuserExample.createCriteria().andOpenidEqualTo(openid);
        List<Wxuser> wxusers = wxuserMapper.selectByExample(wxuserExample);
        if(wxusers.size()<=0){
            Wxuser wxuser=new Wxuser();
            wxuser.setOpenid(openid);
            wxuser.setUserNewTime(new Date());
            wxuser.setUserId(RandomUtil18.Number18());
            wxuser.setUserName("咕咕咕");
            wxuserMapper.insertSelective(wxuser);
            wxUserOpenid.put("userid", wxuser.getUserId());
            Map<String, String> tokenmap=new HashMap<>();
            tokenmap.put("userid",wxUserOpenid.get("userid"));
            String token = JWTUtils.getToken(tokenmap);
            wxUserOpenid.put("token",token);
            return ReturnResult.dataSuccess(wxUserOpenid);
        }else {
            Wxuser wxuser = wxusers.get(0);
            Map<String, String> wxUserOpenidHasExist=new HashMap<>();
            //获取小店
            String userId = wxuser.getUserId();
            StoreExample storeExample=new StoreExample();
            storeExample.createCriteria().andUserIdEqualTo(userId);
            List<Store> stores = storeMapper.selectByExample(storeExample);
            if(stores.size()>0){
                Store store = stores.get(0);
                wxUserOpenidHasExist.put("storeid",store.getId());
            }else {
                wxUserOpenidHasExist.put("storeid","");
            }
            wxUserOpenidHasExist.put("openid",wxuser.getOpenid());
            wxUserOpenidHasExist.put("userid",wxuser.getUserId());
            Map<String, String> tokenmap=new HashMap<>();
            tokenmap.put("userid",wxUserOpenidHasExist.get("userid"));
            String token = JWTUtils.getToken(tokenmap);
            wxUserOpenidHasExist.put("token",token);
            return ReturnResult.dataSuccess(wxUserOpenidHasExist);
        }
    }

    @Override
    public ReturnResult editUserInformation(HttpServletRequest request) {
        String username = request.getParameter("username");
        String local = request.getParameter("local");
        String auth = request.getParameter("auth");
       // String birth = request.getParameter("birth");
        String userid = request.getParameter("userid");
        String phone = request.getParameter("phone");
        Wxuser wxuser=new Wxuser();
        wxuser.setUserPhone(phone);
        wxuser.setUserId(userid);
        wxuser.setUserName(username);
        wxuser.setUserAuth(auth);
        wxuser.setUserLocation(local);
        //wxuser.setUserBirth(DateUtil.parse(birth));
        WxuserExample wxuserExample=new WxuserExample();
        wxuserExample.createCriteria().andUserIdEqualTo(userid);
        int i = wxuserMapper.updateByExampleSelective(wxuser, wxuserExample);
        if(i>0) return ReturnResult.success();
        else    return ReturnResult.error();
    }

    @Override
    public ReturnResult selectUser(HttpServletRequest request) {
        WxuserExample wxuserExample=new WxuserExample();
        wxuserExample.createCriteria().andUserIdEqualTo(request.getParameter("userid"));
        List<Wxuser> wxusers = wxuserMapper.selectByExample(wxuserExample);
        return ReturnResult.dataSuccess(wxusers.get(0));
    }
}
